import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import '../constant.dart';
import 'amap_navi_controller.dart';
import 'amap_navi_options.dart';

const String viewType = '$AMAP_CHANNEL_NAME/AMapNaviView';

typedef void MapCreatedCallback(AMapNaviController controller);

class AMapNaviView extends StatelessWidget {

  final AmapNaviOptions options;

  const AMapNaviView(
      {Key key,
        this.options,
        this.onAMapViewCreated,
        })
      : super(key: key);

  final MapCreatedCallback onAMapViewCreated;

  @override
  Widget build(BuildContext context) {
    final gestureRecognizers = [
      Factory<OneSequenceGestureRecognizer>(
            () => EagerGestureRecognizer(),
      ),
    ].toSet();

    if (Platform.isAndroid) {
      return AndroidView(
        viewType: viewType,
        hitTestBehavior: PlatformViewHitTestBehavior.opaque,
        gestureRecognizers: gestureRecognizers,
        creationParamsCodec: StandardMessageCodec(),
        onPlatformViewCreated: _onViewCreated,
        creationParams: options == null
            ? jsonEncode(AmapNaviOptions(trafficInfoUpdateEnabled:true).toJson())
            : jsonEncode(options.toJson()),
      );
    } else if (Platform.isIOS) {
      return UiKitView(
        viewType: viewType,
        hitTestBehavior: PlatformViewHitTestBehavior.opaque,
        gestureRecognizers: gestureRecognizers,
        creationParamsCodec: StandardMessageCodec(),
        onPlatformViewCreated: _onViewCreated,
        creationParams: options == null
            ? jsonEncode(AmapNaviOptions(trafficInfoUpdateEnabled:true).toJson())
            : jsonEncode(options.toJson()),
      );
    } else {
      return Text(
        '插件未支持的平台',
      );
    }
  }

  void _onViewCreated(int id) {
    final controller = AMapNaviController.withId(id);
    if (onAMapViewCreated != null) {
      onAMapViewCreated(controller);
    }
  }
}
